package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.CategoryDTO;
import com.example.hello.entity.Category;
import com.example.hello.service.CategoryService;
import com.example.hello.service.FileStorageService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/category")
@Tag(name = "景点类别管理", description = "提供景点类别的增删改查接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 添加景点类别
     */
    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "添加景点类别", description = "添加新的景点类别信息，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "添加成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> addCategory(@RequestBody CategoryDTO categoryDTO) {
        try {
            if (categoryDTO.getDescription() != null && categoryDTO.getDescription().length() > 500) {
                return Result.error(400, "类别描述不能超过500个字符");
            }
            return Result.success(categoryService.addCategory(categoryDTO));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 更新景点类别
     */
    @PutMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "更新景点类别", description = "更新现有景点类别信息，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> updateCategory(@RequestBody CategoryDTO categoryDTO) {
        if (categoryDTO.getCategoryId() == null) {
            return Result.error(400, "类别ID不能为空");
        }
        if (categoryDTO.getDescription() != null && categoryDTO.getDescription().length() > 500) {
            return Result.error(400, "类别描述不能超过500个字符");
        }
        try {
            return Result.success(categoryService.updateCategory(categoryDTO));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 删除景点类别
     */
    @DeleteMapping("/{categoryId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "删除景点类别", description = "根据ID删除景点类别，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> deleteCategory(
            @Parameter(description = "景点类别ID", required = true) 
            @PathVariable Integer categoryId) {
        try {
            return Result.success(categoryService.deleteCategory(categoryId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取景点类别详情
     */
    @GetMapping("/{categoryId}")
    @Operation(summary = "获取景点类别详情", description = "根据ID获取景点类别详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", 
                    content = @Content(schema = @Schema(implementation = Category.class)))
    })
    public Result<Category> getCategoryById(
            @Parameter(description = "景点类别ID", required = true) 
            @PathVariable Integer categoryId) {
        return Result.success(categoryService.getCategoryById(categoryId));
    }

    /**
     * 获取所有景点类别
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有景点类别", description = "获取所有景点类别列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<List<Category>> getAllCategories() {
        return Result.success(categoryService.getAllCategories());
    }

    /**
     * 分页获取景点类别列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取景点类别列表", description = "根据条件分页获取景点类别列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<PageInfo<Category>> getCategoryList(
            @Parameter(description = "景点类别名称，支持模糊查询") 
            @RequestParam(value = "categoryName", required = false) String categoryName,
            @Parameter(description = "是否热门") 
            @RequestParam(value = "isHot", required = false) Boolean isHot,
            @Parameter(description = "页码，默认1") 
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小，默认10") 
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        Category category = new Category();
        category.setCategoryName(categoryName);
        category.setIsHot(isHot);
        
        return Result.success(categoryService.getCategoryList(category, pageNum, pageSize));
    }
    
    /**
     * 上传景点类别封面图片
     */
    @PostMapping("/upload/cover")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "上传景点类别封面图片", description = "上传景点类别的封面图片，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, String>> uploadCoverImage(
            @Parameter(description = "封面图片文件", required = true) 
            @RequestParam("file") MultipartFile file) {
        try {
            String objectKey = "category/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String fileUrl = fileStorageService.uploadFile(file, objectKey);
            
            String accessUrl = fileStorageService.generatePresignedUrl(objectKey, 60);
            
            Map<String, String> data = new HashMap<>();
            data.put("url", fileUrl);
            data.put("accessUrl", accessUrl);
            data.put("objectKey", objectKey);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(500, "文件上传失败：" + e.getMessage());
        }
    }
} 